package servlet.action;

import java.io.IOException;
import java.util.Calendar;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.Customer;
import pojo.Order;
import service.CartManager;
import service.OrderManager;
import service.impl.CartManagerFactory;
import service.impl.OrderManagerFactory;

public class PurchaseActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private CartManager cartManager = CartManagerFactory.INSTANCE;
	private OrderManager orderManager = OrderManagerFactory.INSTANCE;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Customer c = (Customer) request.getSession().getAttribute("customer");
		Map<String, Integer> userCart = cartManager.getCart().get(c.getId());
		
		if (userCart != null) {
			for (Map.Entry<String, Integer> e : userCart.entrySet()) {
				Order o = new Order(c.getId(), e.getKey(), e.getValue(), Calendar.getInstance().getTime());
				orderManager.addOrder(o);
			}
		}
		userCart.clear();
		
		request.getRequestDispatcher("../WEB-INF/views/buysuccess.jsp").forward(request, response);
	}

}
